package com.gzhryc.net_marketing.cloud.micro.api.controllers.cloud;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.TreeUtils;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsApplyAuditRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsApplyAuditResponse;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsCancelAuditRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsCancelAuditResponse;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsInfoRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsInfoResponse;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsListRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsListResponse;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsTypeListRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsTypeListResponse;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsUpSaleRequest;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsUpSaleResponse;
import com.gzhryc.net_marketing.api.protocol.goods.GoodsUpdateStateRequest;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketProjectApp;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketSupplier;
import com.gzhryc.net_marketing.cloud.business.services.MarketProjectAppService;
import com.gzhryc.net_marketing.cloud.business.services.MarketSupplierService;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsAuditApply;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsSpace;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoodsSpaceAuditItem;
import com.gzhryc.net_marketing.cloud.goods.dao.db.GoodsType;
import com.gzhryc.net_marketing.cloud.goods.services.CloudGoodsAuditApplyService;
import com.gzhryc.net_marketing.cloud.goods.services.CloudGoodsService;
import com.gzhryc.net_marketing.cloud.goods.services.CloudGoodsSpaceService;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsTypeService;
import com.gzhryc.net_marketing.cloud.goods.services.dto.CloudGoodsSearch;
import com.gzhryc.net_marketing.cloud.micro.api.MicroConstants;
import com.gzhryc.net_marketing.core.enums.EGoodsState;
import com.gzhryc.net_marketing.core.models.GoodsItem;
import com.gzhryc.net_marketing.core.models.GoodsSpaceItem;
import com.gzhryc.net_marketing.core.models.GoodsTypeItem;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;

public class CloudGoodsAPIController {

    static Logger log = Logger.getLogger(CloudGoodsAPIController.class);

    @Route(value = { "/market/cloud_api/v1/goods/list.data" })
    public GoodsListResponse findGoodsList(HttpServletRequest request) {
        GoodsListResponse apiResp = new GoodsListResponse(DefaultAPICodeConstants.NULL_DATA);
        GoodsListRequest apiReq = WebUtils.getJsonRequest(request, GoodsListRequest.class);
        if (apiReq != null) {
            CloudGoodsSearch search = ClassTools.copy(new CloudGoodsSearch(), apiReq.getBody());
            search.setName(apiReq.getBody().getGoodsName());
            search.setState(EGoodsState.PutOnTheShelf.index());

            Long total = CloudGoodsService.self().countBySearch(search);
            apiResp.getBody().setTotal(total);

            List<CloudGoods> data = CloudGoodsService.self().findBySearch(search, apiReq.getBody().getPageNo(), apiReq.getBody().getPageLimit());
            if (data != null && data.size() > 0) {
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS);
                apiResp.getBody().setGoodsList(new ArrayList<>());
                //获取静态资源
                String resDomain = MicroConstants.getResDomain();
                for (CloudGoods goods : data) {
                    GoodsItem item = ClassTools.copy(new GoodsItem(), goods);
                    item.setClassifyName(goods.getClassifyName());
                    //图片路径
                    if (StringTools.isNotBlank(goods.getDetailImgs())) {
                        String[] detailImgArray = goods.getDetailImgPaths();
                        if (detailImgArray != null && detailImgArray.length > 0) {
                            for (int i = 0; i < detailImgArray.length; i++) {
                                detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
                            }
                            item.setDetailImgs(StringUtils.join(detailImgArray, "|"));
                        }
                    }
                    if (StringTools.isNotBlank(goods.getImgs())) {
                        String[] imgArray = goods.getImgPaths();
                        if (imgArray != null && imgArray.length > 0) {
                            for (int i = 0; i < imgArray.length; i++) {
                                imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
                            }
                            item.setImgs(StringUtils.join(imgArray, "|"));
                        }
                    }
                    item.setThumbnailImg(WebUtils.setHttpDomain(resDomain, item.getThumbnailImg()));
                    apiResp.getBody().getGoodsList().add(item);
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/info.data" })
    public GoodsInfoResponse getGoodsInfo(HttpServletRequest request) {
        GoodsInfoResponse apiResp = new GoodsInfoResponse(DefaultAPICodeConstants.NULL_DATA,"暂无数据");
        GoodsInfoRequest apiReq = WebUtils.getJsonRequest(request,GoodsInfoRequest.class);
        if(apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getGoodsCode())) {
        	CloudGoods goods = CloudGoodsService.self().getById(apiReq.getBody().getGoodsCode());
            if(goods != null){
                if(EGoodsState.PutOnTheShelf.index().equals(goods.getState())) {
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS);
                    GoodsItem item = ClassTools.copy(new GoodsItem(), goods);
                    item.setClassifyName(goods.getClassifyName());

                    //获取静态资源
                    String resDomain = MicroConstants.getResDomain();
                    //图片路径
                    if (StringTools.isNotBlank(goods.getDetailImgs())) {
                        String[] detailImgArray = goods.getDetailImgPaths();
                        if (detailImgArray != null && detailImgArray.length > 0) {
                            for (int i = 0; i < detailImgArray.length; i++) {
                                detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
                            }
                            item.setDetailImgs(StringUtils.join(detailImgArray, "|"));
                        }
                    }
                    if (StringTools.isNotBlank(goods.getImgs())) {
                        String[] imgArray = goods.getImgPaths();
                        if (imgArray != null && imgArray.length > 0) {
                            for (int i = 0; i < imgArray.length; i++) {
                                imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
                            }
                            item.setImgs(StringUtils.join(imgArray, "|"));
                        }
                    }
                    item.setThumbnailImg(WebUtils.setHttpDomain(resDomain, item.getThumbnailImg()));

                    List<CloudGoodsSpace> goodsSpaceList = CloudGoodsSpaceService.self().findPutByGoodsId(goods.getId());
                    if (goodsSpaceList != null && goodsSpaceList.size() > 0) {
                        item.setSpaceItemList(new ArrayList<>());
                        for (CloudGoodsSpace goodsSpace : goodsSpaceList) {
                            GoodsSpaceItem spaceItem = ClassTools.copy(new GoodsSpaceItem(), goodsSpace);
                            spaceItem.setStateName(goodsSpace.getStateName());
                            spaceItem.setThumbnailImg(WebUtils.setHttpDomain(resDomain, spaceItem.getThumbnailImg()));
                            item.getSpaceItemList().add(spaceItem);
                        }
                    }
                    apiResp.setBody(item);
                }else {
                    apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,goods.getStateName());
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/audit/apply.do" })
    public GoodsApplyAuditResponse applyGoodsAudit(HttpServletRequest request) {
        GoodsApplyAuditResponse apiResp = new GoodsApplyAuditResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"发布失败，请稍后再试");
        GoodsApplyAuditRequest apiReq = WebUtils.getJsonRequest(request, GoodsApplyAuditRequest.class);
        log.info("发布商品请求：{{0:json}}",apiReq);
        if(apiReq != null) {
            CloudGoodsAuditApply apply = null;
            if(apiReq.getBody().getAuditId() != null){
                apply = CloudGoodsAuditApplyService.self().getById(apiReq.getBody().getAuditId());
                if(apply != null){
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setAuditId(apply.getId());
                    apiResp.getBody().setGoodsCode(apply.getGoodsCode());
                    apiResp.getBody().setAuditState(apply.getAuditState());
                    apiResp.getBody().setAuditNote(apply.getAuditNote());
                }
            }

            if(apply == null){
                apply = ClassTools.copy(new CloudGoodsAuditApply(),apiReq.getBody());
                if(apply.getSupplierId() != null && apply.getPayMoney() != null && StringUtils.isNotBlank(apply.getTypeNames())
                        && StringUtils.isNotBlank(apply.getTypeCodes()) && StringUtils.isNotBlank(apply.getName())) {
                    //检查供应链应用是否存在
                    MarketSupplier supplier = MarketSupplierService.self().getById(apply.getSupplierId());
                    if(supplier == null){
                        apiResp.setMsg("未找到指定的供应链应用信息");
                        return apiResp;
                    }

                    apply.setSupplierName(supplier.getName());

                    //规格参数
                    List<CloudGoodsSpaceAuditItem> spaceAuditItemList = null;
                    if(apiReq.getBody().getSpaceItemList() != null && apiReq.getBody().getSpaceItemList().size() > 0){
                        spaceAuditItemList = new ArrayList<>();
                        for(GoodsSpaceItem item : apiReq.getBody().getSpaceItemList()){
                        	CloudGoodsSpaceAuditItem spaceAuditItem = ClassTools.copy(new CloudGoodsSpaceAuditItem(),item);
                            spaceAuditItem.setGoodsId(apply.getGoodsId());
                            spaceAuditItemList.add(spaceAuditItem);
                        }
                    }

                    apply = CloudGoodsAuditApplyService.self().auditApply(apply,spaceAuditItemList);
                    if (apply != null) {
                        apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setAuditId(apply.getId());
                        apiResp.getBody().setGoodsCode(apply.getGoodsCode());
                        apiResp.getBody().setAuditState(apply.getAuditState());
                        apiResp.getBody().setAuditNote(apply.getAuditNote());
                    }
                }else{
                    apiResp.setMsg("参数错误");
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/audit/cancel.do" })
    public GoodsCancelAuditResponse cancelGoodsAudit(HttpServletRequest request) {
        GoodsCancelAuditResponse apiResp = new GoodsCancelAuditResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"取消发布失败，请稍后再试");
        GoodsCancelAuditRequest apiReq = WebUtils.getJsonRequest(request, GoodsCancelAuditRequest.class);
        log.info("取消发布商品请求：{{0:json}}",apiReq);
        if(apiReq != null && apiReq.getBody().getAuditId() != null) {
            CloudGoodsAuditApply apply = CloudGoodsAuditApplyService.self().getById(apiReq.getBody().getAuditId());
            if(apply == null){
                apiResp.setCode(DefaultAPICodeConstants.NULL_DATA);
                apiResp.setMsg("未找到发布信息");
                return apiResp;
            }

            try {
                if(CloudGoodsAuditApplyService.self().closeAuditById(apply)){
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setAuditId(apply.getId());
                    apiResp.getBody().setGoodsCode(apply.getGoodsCode());
                    apiResp.getBody().setAuditState(apply.getAuditState());
                    apiResp.getBody().setAuditNote(apply.getAuditNote());
                }
            } catch (LogicException e) {
                apiResp.setMsg(e.getMessage());
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/type/list.data" })
    public GoodsTypeListResponse findGoodsTypeList(HttpServletRequest request) {
        GoodsTypeListResponse apiResp = new GoodsTypeListResponse(DefaultAPICodeConstants.NULL_DATA);
        GoodsTypeListRequest apiReq = WebUtils.getJsonRequest(request, GoodsTypeListRequest.class);
        if(apiReq != null) {
            List<GoodsType> data = GoodsTypeService.self().findAllUsable();
            if(data != null && data.size() > 0){
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                List<GoodsTypeItem> items = TreeUtils.byTree(data, new GoodsTypeService.TreeConvertListen());
                apiResp.getBody().setItems(items);
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/state/update.do" })
    public DefaultAPIResponse goodsUpdateSate(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        GoodsUpdateStateRequest apiReq = WebUtils.getJsonRequest(request, GoodsUpdateStateRequest.class);
        log.info("修改商品状态请求：{{0:json}}",apiReq);
        if(apiReq != null && StringTools.isNotBlank(apiReq.getBody().getGoodsCode()) && apiReq.getBody().getState() != null) {
            if(StringTools.isBlank(EGoodsState.note(apiReq.getBody().getState()))){
                apiResp.setMsg("无效的状态");
                return apiResp;
            }
            CloudGoods goods = CloudGoodsService.self().getById(apiReq.getBody().getGoodsCode());
            if(goods == null){
                if(EGoodsState.Delete.index().equals(apiReq.getBody().getState())){
                    apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                    return apiResp;
                }else {
                    apiResp.setCode(DefaultAPICodeConstants.NULL_DATA,"未找到商品信息");
                    return apiResp;
                }
            }
            if(goods.getState().equals(apiReq.getBody().getState())){
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
            }else {
                if(EGoodsState.Delete.index().equals(apiReq.getBody().getState())){
                    try {
                        if(CloudGoodsService.self().logicDelete(goods)){
                            apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else if(EGoodsState.OffTheShelf.index().equals(apiReq.getBody().getState())){
                    //下架商品
                    try {
                        if (CloudGoodsService.self().downGoods(goods.getId())) {
                            apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else {
                    CloudGoods updateEntity = new CloudGoods();
                    updateEntity.setId(goods.getId());
                    updateEntity.setState(apiReq.getBody().getState());
                    try {
                        if (CloudGoodsService.self().updateNotNull(updateEntity)) {
                            apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = { "/market/cloud_api/v1/goods/up_sale/apply.do" })
    public GoodsUpSaleResponse applyGoodsUpSale(HttpServletRequest request) {
        GoodsUpSaleResponse apiResp = new GoodsUpSaleResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"申请失败，请稍后再试");
        GoodsUpSaleRequest apiReq = WebUtils.getJsonRequest(request, GoodsUpSaleRequest.class);
        log.info("网店申请出售商品请求：{{0:json}}",apiReq);
        if(apiReq != null && StringTools.isNotBlank(apiReq.getBody().getGoodsCode()) && apiReq.getBody().getAppId() != null) {
            MarketProjectApp marketApp = MarketProjectAppService.self().getById(apiReq.getBody().getAppId());
            if(marketApp == null){
                apiResp.setMsg("未找到网店信息");
                return apiResp;
            }
            CloudGoods goods = CloudGoodsService.self().getById(apiReq.getBody().getGoodsCode());
            if(goods == null){
                apiResp.setMsg("未找到商品信息");
                return apiResp;
            }
            if(EGoodsState.Delete.index().equals(goods.getState()) || EGoodsState.OffTheShelf.index().equals(goods.getState())){
                apiResp.setMsg("商品已下架");
                return apiResp;
            }else if(EGoodsState.NoInventory.index().equals(goods.getState())) {
                apiResp.setMsg("商品无库存");
                return apiResp;
            }else{
                apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
                GoodsItem item = ClassTools.copy(new GoodsItem(), goods);
                item.setClassifyName(goods.getClassifyName());

                //获取静态资源
                String resDomain = MicroConstants.getResDomain();
                //图片路径
                if (StringTools.isNotBlank(goods.getDetailImgs())) {
                    String[] detailImgArray = goods.getDetailImgPaths();
                    if (detailImgArray != null && detailImgArray.length > 0) {
                        for (int i = 0; i < detailImgArray.length; i++) {
                            detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
                        }
                        item.setDetailImgs(StringUtils.join(detailImgArray, "|"));
                    }
                }
                if (StringTools.isNotBlank(goods.getImgs())) {
                    String[] imgArray = goods.getImgPaths();
                    if (imgArray != null && imgArray.length > 0) {
                        for (int i = 0; i < imgArray.length; i++) {
                            imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
                        }
                        item.setImgs(StringUtils.join(imgArray, "|"));
                    }
                }
                item.setThumbnailImg(WebUtils.setHttpDomain(resDomain, item.getThumbnailImg()));

                List<CloudGoodsSpace> goodsSpaceList = CloudGoodsSpaceService.self().findPutByGoodsId(goods.getId());
                if (goodsSpaceList != null && goodsSpaceList.size() > 0) {
                    item.setSpaceItemList(new ArrayList<>());
                    for (CloudGoodsSpace goodsSpace : goodsSpaceList) {
                        GoodsSpaceItem spaceItem = ClassTools.copy(new GoodsSpaceItem(), goodsSpace);
                        spaceItem.setStateName(goodsSpace.getStateName());
                        spaceItem.setThumbnailImg(WebUtils.setHttpDomain(resDomain, spaceItem.getThumbnailImg()));
                        item.getSpaceItemList().add(spaceItem);
                    }
                }
                apiResp.setBody(item);
            }
        }
        return apiResp;
    }

}
